import fg from 'fast-glob';
import fs from 'fs-extra';
import path from 'path';
import { PrefabParser } from '../unity/PrefabParser.js';
import { toolchain } from '../toolchain.js';

export class PrefabFixer {
    public async removeRedundantNodes(): Promise<void> {
        const prefabRoot = path.join(toolchain.opts.projectRoot, 'Assets');
        const prefabs = await fg('**/*.prefab', { cwd: prefabRoot });
        for (const prefab of prefabs) {
            const file = path.join(prefabRoot, prefab);
            const content = await fs.readFile(file, 'utf-8');
            // 收集用到的fileID
            const results = content.matchAll(/(?<=fileID: )\d+/g);
            const usedFIDMap: { [fileID: string]: true } = {};
            for (const rst of results) {
                usedFIDMap[rst[0]] = true;
            }
            const lines = content.split(/\r?\n/);
            let markDeleted = false, linesToBeDeleted: number[] = [];
            for (let i = 0, len = lines.length; i < len; i++) {
                const rst = lines[i].match(PrefabParser.SectionHeader);
                if (rst != null) {
                    if (!usedFIDMap[rst[2]]) {
                        markDeleted = true;
                    } else {
                        markDeleted = false;
                    }
                }
                if (markDeleted) {
                    linesToBeDeleted.push(i);
                }
            }

            if (linesToBeDeleted.length > 0) {
                console.log('redundant nodes detected:', prefab);
                const newLines = lines.filter((value, index) => !linesToBeDeleted.includes(index));
                await fs.writeFile(file, newLines.join('\n') + '\n', 'utf-8');
            }
        }
    }
}
